package com.dks.repository.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.dks.businessUtil.QsMailUtil;
import com.dks.dto.QsMailJsonDto;
import com.dks.mapper.EvaluateMapper;
import com.dks.mapper.FeedbackSheetMapper;
import com.dks.mapper.QsClassMapper;
import com.dks.mapper.QsMailMapper;
import com.dks.mapper.StudentClassMapper;
import com.dks.mapper.UserClassHourPackageMapper;
import com.dks.models.QsClass;
import com.dks.models.QsMail;
import com.dks.repository.IQsClassRepository;
import com.dks.result.Result;
import com.dks.result.ResultInfo;
import com.dks.result.ResultModel;
import com.dks.util.PageInfo;
import com.dks.vo.qsClass.QsClassVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class QsClassRepository implements IQsClassRepository {

    @Autowired
    private QsClassMapper qsClassMapper;
    @Autowired
    private StudentClassMapper studentClassMapper;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private FeedbackSheetMapper feedbackSheetMapper;

    @Autowired
    private UserClassHourPackageMapper userClassHourPackageMapper;

    @Autowired
    private QsMailMapper qsMailMapper;

    @Override
    public Integer insert(QsClass qsClass) {
        return qsClassMapper.insert(qsClass);
    }

    @Override
    public Integer update(QsClass qsClass) {
        return qsClassMapper.update(qsClass);
    }

    @Override
    public Integer delete(Integer id) {
        return qsClassMapper.delete(id);
    }

    @Override
    public QsClass select(Long id) {
        return qsClassMapper.select(id);
    }

    @Override
    public Integer cntByMap(Map<String, Object> map) {
        return qsClassMapper.cntByMap(map);
    }

    @Override
    public List<Integer> getByMap(Map<String, Object> map) {
        return qsClassMapper.getByMap(map);
    }

    @Override
    public List<QsClass> getByMapList(Map<String, Object> map) {
        return qsClassMapper.getByMapList(map);
    }

    @Override
    public Integer updateByCode(QsClass qsClass) {
        return qsClassMapper.updateByCode(qsClass);
    }

    @Override
    public QsClass selectByBfCode(String bfCode) {
        return qsClassMapper.selectByBfCode(bfCode);
    }


    /**
     * @Author: Ah Nan
     * @Description: 老师上课
     * @Date: 9:52 2020/4/23
     * @Modificd By:
     * @Param: CourseId 课程id
     * @Param: TeacherId 老师id
     * @return:
     * @throw: 请描述异常信息
     */
    @Override
    public ResultModel<Object> addClass(QsClass qsClass) {
        qsClass.setAttendClassStatus(0);
        int row = qsClassMapper.update(qsClass);
        if (row == 1) {
            return Result.makeResult(ResultInfo.SUCCESS, row);
        } else {
            return Result.makeResult(ResultInfo.ERR_DATA_STRUCTURE, row);
        }
    }

    /**
     * @Author: Ah Nan
     * @Description: 获取首页课程列表
     * @Date: 9:52 2020/4/23
     * @Modificd By:
     * @Param: diaryId 日记id
     * @return:
     * @throw: 请描述异常信息
     */
    @Override
    public ResultModel<Object> getCourseTeacherList() {
        Map<String, Object> map = new HashMap<>();
        List<QsClass> qsClassList = qsClassMapper.getByMapList(map);
        return Result.makeResult(ResultInfo.SUCCESS, qsClassList);
    }

    /**
     * @Author: Ah Nan
     * @Description: 获取待上课课程列表
     * @Date: 9:52 2020/4/23
     * @Modificd By:
     * @Param: diaryId 日记id
     * @return:
     * @throw: 请描述异常信息
     */
    @Override
    public ResultModel<Object> getWaitQsClassList() {
        Map<String, Object> map = new HashMap<>();
//        map.put("attendClassStat",)
        List<QsClass> qsClassList = qsClassMapper.getByMapList(map);
        return Result.makeResult(ResultInfo.SUCCESS, qsClassList);
    }


    /**
     * 班级筛选
     * 筛选条件：上课时间（startTime、endTime）、课程类型(courseCategory)、学生id（studentId）
     *
     * @author evan
     */
    @Override
    public ResultModel<PageInfo<QsClass>> listScreening(LocalDateTime startTime, LocalDateTime endTime, Integer studentId,
                                                        String courseCategory, Integer pageNum, Integer pageSize) {
        Page p = PageHelper.startPage(pageNum, pageSize);
        List<QsClass> qsClassList = qsClassMapper.listScreening(startTime, endTime, studentId, courseCategory);
        PageInfo<QsClass> pageInfo = new PageInfo<>(pageNum, pageSize, p.getTotal(), p.getPages(), qsClassList);
        return Result.makeResult(ResultInfo.SUCCESS, pageInfo);
    }

    /***
     * 根据id 获取班级信息
     * @author evan
     */
    @Override
    public ResultModel<QsClass> get(Long id) {
        QsClass qsClass = qsClassMapper.select(id);
        if (qsClass == null) {
            return Result.makeResult(ResultInfo.ERR_CLASS_001);
        } else {
            return Result.makeResult(ResultInfo.SUCCESS, qsClass);
        }
    }

    /***
     * 根据id 获取班级信息
     * @author evan
     */
    @Override
    public ResultModel<QsClassVo> getDetail(Long id, long userId) {
        QsClassVo qsClassVo = qsClassMapper.getDetail(id);
        if (qsClassVo == null) {
            return Result.makeResult(ResultInfo.ERR_CLASS_001);
        }
        if (qsClassVo.getTeacherId() == userId) {
            Integer qsClassAttendNum = studentClassMapper.countClassAttendNum(qsClassVo.getId());
            Integer classLeaveNum = studentClassMapper.countClassLeaveNum(qsClassVo.getId());
            qsClassVo.setClassAttendNum(qsClassAttendNum); /** 上课总人数（固定位+临时位+体验位） */
            qsClassVo.setClassShouldAttendNum(qsClassAttendNum - classLeaveNum); /** 应上课总人数(上课总人数-请假的) */
            qsClassVo.setEvaluateAppraice(null); /** 家长评价得分 */

            qsClassVo.setEvaluateNum(evaluateMapper.countEvaluateNum(qsClassVo.getId())); /** 家长评价-已评价人数 */
            qsClassVo.setTaskCorrectNum(studentClassMapper.countTaskCorrectNum(qsClassVo.getId())); /** 作业-已批改人数 */
            qsClassVo.setFeedbackSheetNum(feedbackSheetMapper.countFeedbackSheetNum(qsClassVo.getId()));/** 课堂反馈-已填写数量	 */
        }
        return Result.makeResult(ResultInfo.SUCCESS, qsClassVo);
    }

    /**
     * @Author: Ah Nan
     * @Description: 老师下课
     * @Date: 9:52 2020/4/23
     * @Modificd By:
     * @Param: qsClassId 课程id
     * 1、打下课状态，qs_class：attend_class_status 上课状态:0上课,1下课
     * 2、该班级对应的学生的课时包冻结课时-消耗课时，已用课时数+消耗课时，可用课时数-消耗课时。
     * 3、发送站内信
     * @return:
     * @throw: 请描述异常信息
     */
    @Transactional
    @Override
    public ResultModel<Object> classIsOver(QsClass qsClass) {

        QsClass qsClassR = qsClassMapper.select(qsClass.getId());

        if (null != qsClassR.getAttendClassStatus() && 1 == qsClassR.getAttendClassStatus()) {
            return Result.makeResult(ResultInfo.ERR_DATA_STRUCTURE, "该课程已经下课不可重复操作");
        }

        qsClass.setAttendClassStatus(1);
        qsClassMapper.update(qsClass);
        Map<String, Object> map = new HashMap<>();
        map.put("qsClassId", qsClass.getId());
        //查找所有符合条件的id
        List<Integer> uchpId = userClassHourPackageMapper.userClassHourPackageIdList(map);
        //执行批量更新操作

        Map<String, Object> mapU = new HashMap<>();
        mapU.put("idList", uchpId);
        mapU.put("periodBasic", qsClassR.getPeriodBasic());
        int row = userClassHourPackageMapper.updateCountHour(mapU);

        if (row == 0) {
            return Result.makeResult(ResultInfo.ERR_DATA_STRUCTURE, row);
        } else {
//            QsMailJsonDto qsMailJsonDto = qsMailMapper.selectQsMailJsonDto(qsClassR.getTeacherId());
//            qsMailJsonDto.setPeriodBasic(qsClassR.getPeriodBasic());
            QsMail qsMail = new QsMail(qsClassR.getTeacherId(), 1, "下课提醒", "您的课程已经下课，立即完成作业和教室评价获取奖励吧！", qsClass.getId());
            QsMailUtil qsMailUtil = new QsMailUtil();
            qsMailUtil.insertQsMail(qsMail);
            return Result.makeResult(ResultInfo.SUCCESS, row);
        }
    }
}
